"use client";

import { useContext, useState } from "react";
import {
  Button,
  Input,
  FormControl,
  FormLabel,
  FormErrorMessage,
  useDisclosure,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalFooter,
  useToast,
  Box,
  Text,
  ModalCloseButton,
} from "@chakra-ui/react";
import { MainContext } from "@/src/providers/MainProvider";
import { MouseProfile } from "@/src/types/types.v1.d";
import _ from "lodash";
import { AddIcon } from "@chakra-ui/icons";
import { ImportIcon } from "../Icons/ImportIcon";
import { useTranslation } from "@/src/i18n";

// 配置相关常量
const configLimits = {
  maxProfiles: 5,
} as const;

const CreateConfig = () => {
  const { profile, profileIndex, deviceName } = useContext(MainContext);
  const { isOpen, onOpen, onClose } = useDisclosure();
  const toast = useToast();

  const [checkMsg, setCheckMsg] = useState("");
  const [editName, setEditName] = useState("");
  const { t } = useTranslation("");
  // 创建配置
  const createConfig = () => {
    onOpen();
    setEditName("");
  };

  // 校验配置名称
  const checkProfileName = (name: string) => {
    setEditName(name);

    // 检查名称是否为空
    if (!name.trim()) {
      setCheckMsg(t("lengthNotAllowEmpty"));
      return;
    }

    // 检查名称长度
    if (name.length < 1 || name.length > 20) {
      setCheckMsg(t("lengthLimit"));
      return;
    }

    // 检查特殊字符
    const specialChars = /[<>:"/\\|?*\x00-\x1F]/;
    if (specialChars.test(name)) {
      setCheckMsg("配置名称不能包含特殊字符");
      return;
    }

    // 检查名称是否已存在
    if (profile.profiles.find((p) => p.name === name)) {
      setCheckMsg(t("haveSameName"));
      return;
    }

    // 所有检查通过
    setCheckMsg("");
  };

  // 创建配置
  const handleSubmit = () => {
    // 再次进行名称校验
    if (!editName.trim()) {
      setCheckMsg(t("lengthNotAllowEmpty"));
      return;
    }

    if (editName.length < 1 || editName.length > 20) {
      setCheckMsg(t("lengthLimit"));
      return;
    }

    const specialChars = /[<>:"/\\|?*\x00-\x1F]/;
    if (specialChars.test(editName)) {
      setCheckMsg("配置名称不能包含特殊字符");
      return;
    }

    if (profile.profiles.find((p) => p.name === editName)) {
      setCheckMsg(t("haveSameName"));
      return;
    }

    profile.createProfile(editName, profileIndex);
    toast({
      title: t("createSuccess"),
      status: "success",
      duration: 3000,
      isClosable: true,
      position: "top",
      containerStyle: {
        marginTop: "60px",
      },
    });
    setCheckMsg("");
    onClose();
  };

  // 生成唯一配置名
  const generateUniqueName = (
    baseName: string,
    profiles: MouseProfile[]
  ): string => {
    let newName = baseName;
    let counter = 1;
    while (profiles.some((profile) => profile.name === newName)) {
      newName = `${baseName}${counter++}`;
    }
    return newName;
  };

  // 处理文件上传
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.readAsText(file, "UTF-8");

    reader.onload = (e) => {
      try {
        const result = e.target?.result as string;
        if (!result) return;

        const importData = JSON.parse(result);

        // 检查导入的配置是否包含设备型号信息
        if (!importData.deviceModel || !importData.profileData) {
          toast({
            title: t("errorType"),
            status: "error",
            duration: 3000,
            position: "top",
            containerStyle: {
              marginTop: "60px",
            },
            isClosable: true,
          });
          return;
        }

        // 检查设备型号是否匹配
        if (importData.deviceModel !== deviceName) {
          toast({
            title: t("notApplicable"),
            status: "error",
            duration: 3000,
            position: "top",
            containerStyle: {
              marginTop: "60px",
            },
            isClosable: true,
          });
          return;
        }

        // 检查配置数量是否达到上限
        if (profile.profiles.length >= configLimits.maxProfiles) {
          toast({
            title: t("importFail"),
            description: t("maxLimit"),
            status: "error",
            duration: 3000,
            position: "top",
            containerStyle: {
              marginTop: "60px",
            },
            isClosable: true,
          });
          return;
        }

        // 检查并生成唯一的配置名称
        let newName = importData.profileData.name;
        let counter = 1;
        while (profile.profiles.some((p) => p.name === newName)) {
          newName = `${importData.profileData.name}(${counter})`;
          counter++;
        }

        const newProfiles = [
          ...profile.profiles,
          {
            ...importData.profileData,
            name: newName,
            active: false,
          },
        ];

        profile.setProfiles(_.cloneDeep(newProfiles));

        toast({
          title: t("importSuccess"),
          status: "success",
          duration: 3000,
          position: "top",
          containerStyle: {
            marginTop: "60px",
          },
          isClosable: true,
        });
      } catch (error) {
        toast({
          title: t("importFail"),
          description: t("failTypeError"),
          status: "error",
          duration: 3000,
          position: "top",
          containerStyle: {
            marginTop: "60px",
          },
          isClosable: true,
        });
      }
    };

    // 清空 input 值，允许重复导入同一文件
    event.target.value = "";
  };
  return (
    <>
      <Box className="flex justify-between gap-2 w-full">
        <Button
          leftIcon={<AddIcon className="w-[16px] h-[16px]" />}
          onClick={createConfig}
          disabled={profile.profiles?.length >= configLimits.maxProfiles}
          className="primary-btn !h-10 !font-family-msyh !text-[14px] !rounded-[8px] w-[96px]"
        >
          {t("createConfig")}
        </Button>
        <Box className="relative">
          <input
            type="file"
            onChange={handleFileUpload}
            accept=".json"
            disabled={profile.profiles?.length >= configLimits.maxProfiles}
            className={`absolute top-0 left-0 w-full h-full opacity-0 z-10 ${
              profile.profiles?.length >= configLimits.maxProfiles
                ? "cursor-not-allowed"
                : "cursor-pointer"
            }`}
          />
          <Button
            variant="outline"
            leftIcon={<ImportIcon className="w-[16px] h-[16px] fill-white" />}
            className="font-family-msyh !text-[14px] !rounded-[8px] w-[96px] !text-white"
            disabled={profile.profiles?.length >= configLimits.maxProfiles}
            height="40px"
            sx={{
              opacity:
                profile.profiles?.length >= configLimits.maxProfiles ? 0.4 : 1,
              _disabled: {
                cursor: "not-allowed",
                "&:hover": {
                  bg: "transparent",
                },
              },
              border: "1px solid #D7DEE3",
            }}
          >
            {t("import")}
          </Button>
        </Box>
      </Box>

      <Modal isOpen={isOpen} onClose={onClose} isCentered>
        <ModalOverlay />
        <ModalContent minWidth="500px" height="260px">
          <ModalHeader
            fontSize="16px"
            display="flex"
            justifyContent="space-between"
            alignItems="center"
            // bg="#211a31"
            height="48px"
            px="24px"
          >
            {t("createConfigName")}
            <ModalCloseButton position="relative" top="unset" right="unset" />
          </ModalHeader>
          <ModalBody px="24px" pt="24px">
            <Text color="white" fontSize="14px" mb="16px" lineHeight="20px">
              {t("createConfigTip")}
            </Text>
            <FormControl isInvalid={!!checkMsg}>
              <Input
                value={editName}
                onChange={(e) => checkProfileName(e.target.value)}
                placeholder={t("enterConfigName")}
                maxLength={20}
                fontSize="14px"
                height="40px"
                className="pr-[45px]"
                sx={{
                  "&:focus-visible": {
                    boxShadow: "none",
                    borderColor: checkMsg ? "#E53E3E" : "#0066FF",
                  },
                }}
              />
              <Text
                position="absolute"
                right="10px"
                top="10px"
                color={checkMsg ? "#E53E3E" : "gray.500"}
                fontSize="14px"
              >
                {editName.length}/20
              </Text>
              {checkMsg && (
                <FormErrorMessage fontSize="12px">{checkMsg}</FormErrorMessage>
              )}
            </FormControl>
          </ModalBody>

          <ModalFooter
            px="24px"
            pb="24px"
            display="flex"
            justifyContent="center"
            gap="12px"
          >
            <Button
              className="primary-btn"
              onClick={handleSubmit}
              width="120px"
              height="40px"
              fontSize="16px"
            >
              {t("ok")}
            </Button>
            <Button
              variant="outline"
              onClick={onClose}
              width="120px"
              height="40px"
              fontSize="16px"
              border="1px solid #D7DEE3"
            >
              {t("cancel")}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  );
};

export default CreateConfig;
